<?php
//消费券及领取操作

namespace App\Repositories;

use App\Models\DealModel;
use App\Models\RiskCheckModel;
use App\Models\StrategyModel;
use http\Env\Request;


class DealRepository extends BaseRepository
{
    public function __construct()
    {

    }

    /**
     * @param $id
     * @return false
     */
    public function getDealInfo ($id)
    {
        $user = request()->user();
        if (empty($id)) {
            return false;
        }
        $operate = DealModel::where('id', $id)
            ->where('admin_id', $user['id'])
            ->select()
            ->first();
        return $operate;
    }

    /**
     * 配置搜索条件
     * @param $params
     * @return array[]
     */
    public function getFilter ($params) {
        $user = request()->user();
        $where = [
            ['admin_id', $user['id']]
        ];
        $whereBetween = [];
        if (!empty($params['traded_at'])) {
            $whereBetween[] = [
                'traded_at', $params['traded_at']
            ];
        }
        if (!empty($params['operate_id'])) {
            $where[] = [
                'operate_id', $params['operate_id']
            ];
        }
        if (!empty($params['market_index_status'])) {
            $where[] = [
                'market_index_status', $params['market_index_status']
            ];
        }
        if (!empty($params['is_short_covering'])) {
            $where[] = [
                'is_short_covering', $params['is_short_covering']
            ];
        }
        if (!empty($params['strategy_id'])) {
            $where[] = [
                'strategy_id', $params['strategy_id']
            ];
        }
        if (!empty($params['stock_type'])) {
            $where[] = [
                'stock_type', $params['stock_type']
            ];
        }
        if (!empty($params['deal_type'])) {
            $where[] = [
                'deal_type', $params['deal_type']
            ];
        }
        if (!empty($params['stock_code'])) {
            $where[] = [
                'stock_code', 'like', '%' . $params['stock_code'] . '%'
            ];
        }
        if (!empty($params['stock_name'])) {
            $where[] = [
                'stock_name', 'like', '%' . $params['stock_name'] . '%'
            ];
        }
        return [
            'where' => $where,
            'whereBetween' => $whereBetween
        ];
    }

    /**
     * 获取列表
     * @param $params
     * @return array
     */
    public function getList ($params)
    {
        $filter = $this->getFilter($params);
        $orders = $this->_getOrders($params);
        $lists = $this->getListItems(DealModel::query(), $filter, $params['page_size'] ?? 20, ['*'], 'page', $orders);
        return $this->_formatList($lists);
    }

    /**
     * @param $lists
     * @return mixed
     */
    private function _formatList ($lists)
    {
        $user = request()->user();
        $strategies = StrategyModel::where('admin_id', $user['id'])
            ->pluck('name', 'id');
        foreach ($lists['list'] as $key => &$list) {
            $list['price_string'] = $list['price']. '元';
            $list['deal_money_string'] = $list['deal_money'] / 100 . '元';
            $list['traded_at_string'] = substr($list['traded_at'], 0, 16);
            $list['market_index_env_string'] = DealModel::MARKET_INDEX_STATUSES[$list['market_index_status']];
            $list['is_short_covering_string'] = DealModel::COVERIN[$list['is_short_covering']];
            $list['deal_type_string'] = DealModel::DEAL_TYPES[$list['deal_type']];
            $list['strategy_string'] = $strategies[$list['strategy_id']];
            $list['stock_type_string'] = DealModel::STOCK_TYPES[$list['stock_type']];
        }
        return $lists;
    }

    /**
     * @param $params
     * @return mixed
     */
    public function save ($params)
    {
        $params = $this->formatSaveParams($params);
        return $this->saveOrUpdate('DealModel', $params);
    }

    /**
     * @param $params
     * @return mixed
     */
    private function formatSaveParams ($params)
    {
        // 传过来为空字符串，laravel会默认设置为null，手动设置为空字符串
        foreach ($params as $key => $value) {
            if (empty($value)) {
                $params[$key] = '';
            }
        }
        if (empty($params['code_prefix'])) {
            $followRepo = new FollowRepository();
            $params['code_prefix'] = $followRepo->getStockPrefixByCode($params['stock_code']);
        }
        $params['deal_money'] = $params['share_number'] * $params['price'];
        $params['stock_type'] = DealModel::STOCK_TYPE_KEYS[$params['code_prefix']];
        $params['lot_number'] = $params['share_number'] / 100;
        $params['opening_bank_id'] = 1;
        $params['stock_software_id'] = 1;
        $params['admin_id'] = 1;
        return $params;
    }

    /**
     * @param $dealId
     * @param $price
     * @param $shareNumber
     * @return bool
     */
    public function checkPriceChange ($dealId, $price, $shareNumber)
    {
        $dealCount = 0;
        if ($dealId) {
            $dealCount = DealModel::where('id', $dealId)
                ->where('price', $price)
                ->where('share_number', $shareNumber)
                ->count();
        }
        return !$dealCount;
    }

    /**
     * 更新交易表中的risk_check_id;
     * @param $code
     * @return mixed
     */
    public function setRiskCheckId ($code)
    {
        $rst = false;
        $riskCheckId = RiskCheckModel::where('stock_code', $code)
            ->whereDate('created_at', today())                      // 当日创建的
            ->value('id');
        $deal = DealModel::where('stock_code', $code)
            ->whereDate('created_at', today())                      // 当然创建的自动关联
            ->first();
        if ($deal) {
            $deal->risk_check_id = $riskCheckId;
            $rst = $deal->save();
        }
        return $rst;
    }
}
